﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace DrinkcounterUi
{
    public class Google
    {
        public static Image GetGauge(Person person, int width, float gaugeMaxValue, Color color)
        {
            if (width < 10) width = 10;

            string url =
                @"http://chart.apis.google.com/chart
                   ?chxr=0,0,{3}
                   &chxt=y
                   &chs={1}x{2}
                   &cht=gm
                   &chds=0,{3}
                   &chf=bg,s,65432100
                   &chco=FF9900,008000|FFCC33|AA0033
                   &chl={0}
                   &chco={4}
                   &chd=t:{0}"
                .Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", "");

            int w = Math.Min(width, 750);
            url = string.Format(url, 
                person.Alcohol.ToString("F", CultureInfo.InvariantCulture), 
                w, 
                w / 2, 
                gaugeMaxValue,
                color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2")
                );

            return GetImage(url);
        }

        private static Image GetImage(string url)
        {
            HttpWebRequest request = null;
            WebResponse response = null;
            Stream stream = null;
            Image image;

            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.AllowWriteStreamBuffering = true;

                response = request.GetResponse();
                stream = response.GetResponseStream();

                image = Image.FromStream(stream);
            }
            finally
            {
                try { stream.Close(); }
                catch { }
                try { response.Close(); }
                catch { }
            }

            return image;
        }

        public static Image GetChart(Person person, List<PersonHistory> personHistories, int width, int maxWidth, int maxAlcohol, Color color)
        {
            if (width < 10) width = 10;

            string url =
                @"http://chart.apis.google.com/chart
                   ?chxr=0,0,5
                   &chf=bg,s,65432100
                   &chxs=0,110101,11.5,0,l,676767
                   &chxt=y
                   &chs={1}x{2}
                   &cht=lxy
                   &chds=0,{3},0,{4}
                   &chd=t:{0}
                   &chdlp=b
                   &chg={5},{6},0,0
                   &chco={7}
                   &chls=1"
                .Replace(Environment.NewLine, "").Replace(" ", "").Replace("\t", "");

            int w = Math.Min(width, 750);
            var asd = GetDataFromHistories(personHistories, person.Name, maxWidth);
            if (string.IsNullOrWhiteSpace(asd))
                return null;


            url = string.Format(url, 
                asd, 
                w, 
                w / 2, 
                maxWidth,
                maxAlcohol,
                100 / (maxWidth / 60),
                100 / maxAlcohol,
                color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2")
                );

            return GetImage(url);
        }

        private static string GetDataFromHistories(List<PersonHistory> personHistories, string name, int maxWidth)
        {
            /*
            while (personHistories.Count < 16)
                personHistories.Add(new PersonHistory() { Timestamp = DateTime.MinValue, Alcohol = 0, Drinks = 0, Name = name });
            */
            var values = personHistories.Where(personHistory => personHistory.Timestamp >= DateTime.Now - TimeSpan.FromMinutes(maxWidth)).ToList();
            if (values.Count == 0) return "";

            values.Sort((ph1, ph2) => DateTime.Compare(ph1.Timestamp, ph2.Timestamp));
    
            /*
            while (personHistories.Count > 16)
                personHistories.RemoveAt(0);
            */

            StringBuilder y = new StringBuilder();
            StringBuilder x = new StringBuilder();
            foreach (var personHistory in values)
            {
                y.Append(personHistory.Alcohol.ToString("F", CultureInfo.InvariantCulture));
                y.Append(',');

                double minutes = maxWidth - (DateTime.Now - personHistory.Timestamp).TotalMinutes;
                x.Append(minutes.ToString("F", CultureInfo.InvariantCulture));
                x.Append(',');
            }
            return x.ToString(0, x.Length - 1) + "|" + y.ToString(0, y.Length - 1);
        }
    }
}
